<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList"
      :search-params="searchParams"
    />

    <div class="table-layout">
      <el-card shadow="never">
        <div class="statistics-box">
          <el-row :gutter="20">
            <el-col :span="4">
              <div class="stat-card">
                <div class="stat-title">总订单数</div>
                <div class="stat-value">{{ statistics.totalOrders || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="stat-card">
                <div class="stat-title">待付款</div>
                <div class="stat-value">{{ statistics.byStatus?.pendingPayment || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="stat-card">
                <div class="stat-title">待发货</div>
                <div class="stat-value">{{ statistics.byStatus?.paid || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="stat-card">
                <div class="stat-title">已发货</div>
                <div class="stat-value">{{ statistics.byStatus?.shipped || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="stat-card">
                <div class="stat-title">已完成</div>
                <div class="stat-value">{{ statistics.byStatus?.completed || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="stat-card">
                <div class="stat-title">已取消</div>
                <div class="stat-value">{{ statistics.byStatus?.cancelled || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            @selection-change="onSelect"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column align="center" label="订单号" prop="order_no" width="180" />
            <el-table-column align="center" label="用户" width="120">
              <template slot-scope="scope">
                {{ scope.row.user ? scope.row.user.nickName : '-' }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="总金额" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.total_amount }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="积分" width="100">
              <template slot-scope="scope">
                {{ scope.row.total_points || 0 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="支付方式" width="120">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.payment_type === 0" type="primary">在线支付</el-tag>
                <el-tag v-else-if="scope.row.payment_type === 1" type="success">积分支付</el-tag>
                <el-tag v-else-if="scope.row.payment_type === 2" type="warning">混合支付</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="配送方式" width="120">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.shipping_type === 0" type="primary">同城配送</el-tag>
                <el-tag v-else-if="scope.row.shipping_type === 1" type="success">快递</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="订单状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" type="info">待付款</el-tag>
                <el-tag v-else-if="scope.row.status === 1" type="warning">待发货</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="primary">已发货</el-tag>
                <el-tag v-else-if="scope.row.status === 3" type="success">已完成</el-tag>
                <el-tag v-else-if="scope.row.status === 4" type="danger">已取消</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="微信支付状态" width="120">
              <template slot-scope="scope">
                <template v-if="scope.row.payment_type === 0">
                  <el-tag v-if="scope.row.wx_pay_status === 'not_paid'" type="info">未支付</el-tag>
                  <el-tag v-else-if="scope.row.wx_pay_status === 'paid'" type="success">已支付</el-tag>
                  <el-tag v-else-if="scope.row.wx_pay_status === 'refund_requested'" type="warning">退款中</el-tag>
                  <el-tag v-else-if="scope.row.wx_pay_status === 'refunded'" type="danger">已退款</el-tag>
                  <span v-else>-</span>
                </template>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.create_time | dateFormat }}
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="280">
              <template slot-scope="scope">
                <el-button type="text" @click="viewOrder(scope.row)">查看</el-button>
                <el-button 
                  v-if="scope.row.status === 1" 
                  type="text" 
                  @click="shipOrder(scope.row)"
                >发货</el-button>
                <el-button 
                  v-if="scope.row.status === 2" 
                  type="text" 
                  @click="completeOrder(scope.row)"
                >完成</el-button>
                <el-button 
                  v-if="scope.row.status === 0" 
                  type="text" 
                  style="color: #F82222" 
                  @click="cancelOrder(scope.row)"
                >取消</el-button>
                <el-button 
                  v-if="scope.row.status === 1 && scope.row.payment_type === 0 && scope.row.wx_pay_status === 'paid'" 
                  type="text" 
                  style="color: #E6A23C" 
                  @click="refundOrder(scope.row)"
                >退款</el-button>
                <el-button 
                  v-if="scope.row.payment_type === 0 && scope.row.wx_pay_status === 'paid'" 
                  type="text" 
                  @click="queryWxPayment(scope.row)"
                >查询支付</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <!-- 查看订单详情 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder">
        <div class="order-info">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">订单号：</span>
                <span>{{ currentOrder.order_no }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">用户：</span>
                <span>{{ currentOrder.user ? currentOrder.user.nickName : '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">订单状态：</span>
                <span>
                  <el-tag v-if="currentOrder.status === 0" type="info">待付款</el-tag>
                  <el-tag v-else-if="currentOrder.status === 1" type="warning">待发货</el-tag>
                  <el-tag v-else-if="currentOrder.status === 2" type="primary">已发货</el-tag>
                  <el-tag v-else-if="currentOrder.status === 3" type="success">已完成</el-tag>
                  <el-tag v-else-if="currentOrder.status === 4" type="danger">已取消</el-tag>
                </span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">支付方式：</span>
                <span>
                  <el-tag v-if="currentOrder.payment_type === 0" type="primary">在线支付</el-tag>
                  <el-tag v-else-if="currentOrder.payment_type === 1" type="success">积分支付</el-tag>
                  <el-tag v-else-if="currentOrder.payment_type === 2" type="warning">混合支付</el-tag>
                </span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">配送方式：</span>
                <span>
                  <el-tag v-if="currentOrder.shipping_type === 0" type="primary">同城配送</el-tag>
                  <el-tag v-else-if="currentOrder.shipping_type === 1" type="success">快递</el-tag>
                </span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span>{{ currentOrder.create_time | dateFormat }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">总金额：</span>
                <span>¥{{ currentOrder.total_amount }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">积分：</span>
                <span>{{ currentOrder.total_points || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">运费：</span>
                <span>¥{{ currentOrder.shipping_fee || 0 }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="order-info">
          <h3>收货信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">收货人：</span>
                <span>{{ currentOrder.recipient_name }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">联系电话：</span>
                <span>{{ currentOrder.recipient_phone }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">收货地址：</span>
                <span>{{ currentOrder.recipient_address }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-if="currentOrder.status >= 2" class="order-info">
          <h3>物流信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">物流公司：</span>
                <span>{{ currentOrder.shipping_company }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">物流单号：</span>
                <span>{{ currentOrder.tracking_number }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">发货时间：</span>
                <span>{{ currentOrder.shipping_time | dateFormat }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="order-info">
          <h3>商品信息</h3>
          <el-table
            :data="currentOrder.details || []"
            border
            style="width: 100%"
          >
            <el-table-column align="center" label="商品图片" width="100">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.product_image"
                  style="width: 60px; height: 60px"
                  :src="scope.row.product_image"
                  :preview-src-list="[scope.row.product_image]"
                ></el-image>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称" />
            <el-table-column label="价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column label="积分" width="100">
              <template slot-scope="scope">
                {{ scope.row.points_price || 0 }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column label="小计" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.subtotal }}
                <span v-if="scope.row.subtotal_points">
                  + {{ scope.row.subtotal_points }}积分
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-if="currentOrder.remark" class="order-info">
          <h3>备注</h3>
          <p>{{ currentOrder.remark }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 发货弹窗 -->
    <el-dialog
      title="订单发货"
      :visible.sync="shipVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="shipForm" :rules="shipRules" ref="shipFormRef" label-width="100px">
        <el-form-item label="物流公司" prop="shipping_company">
          <el-input v-model="shipForm.shipping_company" placeholder="请输入物流公司"></el-input>
        </el-form-item>
        <el-form-item label="物流单号" prop="tracking_number">
          <el-input v-model="shipForm.tracking_number" placeholder="请输入物流单号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipVisible = false">取 消</el-button>
        <el-button type="primary" :loading="shipLoading" @click="submitShip">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 取消订单弹窗 -->
    <el-dialog
      title="取消订单"
      :visible.sync="cancelVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="cancelForm" :rules="cancelRules" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="remark">
          <el-input 
            type="textarea" 
            v-model="cancelForm.remark" 
            placeholder="请输入取消原因"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelVisible = false">取 消</el-button>
        <el-button type="primary" :loading="cancelLoading" @click="submitCancel">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 退款弹窗 -->
    <el-dialog
      title="申请退款"
      :visible.sync="refundVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="refundForm" :rules="refundRules" ref="refundForm" label-width="100px">
        <el-form-item label="退款金额" prop="refund_amount">
          <el-input-number 
            v-model="refundForm.refund_amount" 
            :min="0.01" 
            :max="currentOrder ? currentOrder.total_amount : 0" 
            :precision="2" 
            :step="0.01"
          ></el-input-number>
          <span class="amount-tip">最大可退金额: ¥{{ currentOrder ? currentOrder.total_amount : 0 }}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input type="textarea" v-model="refundForm.reason" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundVisible = false">取消</el-button>
        <el-button type="primary" :loading="refundLoading" @click="submitRefund">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http } from "@/api";

export default {
  name: "OfficeOrderIndex",
  mixins: [crud],
  data() {
    return {
      request: http.officeOrder,
      searchList: [
        {
          label: '订单号',
          prop: 'order_no',
          name: 'input',
          clearable: true
        },
        {
          label: '订单状态',
          prop: 'status',
          name: 'select',
          clearable: true,
          options: [
            { label: '待付款', value: 0 },
            { label: '待发货', value: 1 },
            { label: '已发货', value: 2 },
            { label: '已完成', value: 3 },
            { label: '已取消', value: 4 }
          ]
        },
        {
          label: '支付方式',
          prop: 'payment_type',
          name: 'select',
          clearable: true,
          options: [
            { label: '在线支付', value: 0 },
            { label: '积分支付', value: 1 },
            { label: '混合支付', value: 2 }
          ]
        },
        {
          label: '微信支付状态',
          prop: 'wx_pay_status',
          name: 'select',
          clearable: true,
          options: [
            { label: '未支付', value: 'not_paid' },
            { label: '已支付', value: 'paid' },
            { label: '退款中', value: 'refund_requested' },
            { label: '已退款', value: 'refunded' }
          ]
        },
        {
          label: '配送方式',
          prop: 'shipping_type',
          name: 'select',
          clearable: true,
          options: [
            { label: '同城配送', value: 0 },
            { label: '快递', value: 1 }
          ]
        },
        {
          label: '下单时间',
          prop: 'timeValue',
          name: 'date',
          dateType: 'datetimerange',
          valueFormat: 'yyyy-MM-dd HH:mm:ss'
        }
      ],
      searchParams: {
        order_no: '',
        status: '',
        payment_type: '',
        wx_pay_status: '',
        shipping_type: '',
        timeValue: []
      },
      defaultParams: {
        type: 1
      },
      statistics: {},
      detailVisible: false,
      currentOrder: null,
      shipVisible: false,
      shipLoading: false,
      shipForm: {
        id: '',
        shipping_company: '',
        tracking_number: ''
      },
      shipRules: {
        shipping_company: [{ required: true, message: '请输入物流公司', trigger: 'blur' }],
        tracking_number: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
      },
      cancelVisible: false,
      cancelLoading: false,
      cancelForm: {
        id: '',
        remark: ''
      },
      cancelRules: {
        remark: [{ required: true, message: '请输入取消原因', trigger: 'blur' }]
      },
      refundVisible: false,
      refundLoading: false,
      refundForm: {
        id: '',
        refund_amount: 0,
        reason: ''
      },
      refundRules: {
        refund_amount: [{ required: true, message: '请输入退款金额', trigger: 'blur' }],
        reason: [{ required: true, message: '请输入退款原因', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.getStatistics();
  },
  methods: {
    getStatistics() {
      http.officeOrder.statistics().then(res => {
        this.statistics = res.data;
      });
    },
    viewOrder(row) {
      this.detailVisible = true;
      http.officeOrder.read(row.id).then(res => {
        this.currentOrder = res.data;
      });
    },
    shipOrder(row) {
      this.shipVisible = true;
      this.shipForm = {
        id: row.id,
        shipping_company: '',
        tracking_number: ''
      };
    },
    submitShip() {
      this.$refs.shipFormRef.validate(valid => {
        if (valid) {
          this.shipLoading = true;
          http.officeOrder.ship(this.shipForm).then(res => {
            this.$message.success('发货成功');
            this.shipVisible = false;
            this.onSearch();
            this.getStatistics();
          }).finally(() => {
            this.shipLoading = false;
          });
        }
      });
    },
    completeOrder(row) {
      this.$confirm('确认将该订单标记为已完成?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.officeOrder.complete({ id: row.id }).then(res => {
          this.$message.success('操作成功');
          this.onSearch();
          this.getStatistics();
        });
      });
    },
    cancelOrder(row) {
      this.cancelVisible = true;
      this.cancelForm = {
        id: row.id,
        remark: ''
      };
    },
    submitCancel() {
      this.$refs.cancelFormRef.validate(valid => {
        if (valid) {
          this.cancelLoading = true;
          http.officeOrder.cancel(this.cancelForm).then(res => {
            this.$message.success('取消成功');
            this.cancelVisible = false;
            this.onSearch();
            this.getStatistics();
          }).finally(() => {
            this.cancelLoading = false;
          });
        }
      });
    },
    refundOrder(row) {
      this.currentOrder = row;
      this.refundForm.id = row.id;
      this.refundForm.refund_amount = row.total_amount;
      this.refundForm.reason = '';
      this.refundVisible = true;
    },
    async submitRefund() {
      this.$refs.refundForm.validate(async (valid) => {
        if (valid) {
          this.refundLoading = true;
          try {
            const res = await http.officeOrder.refundOrder({
              id: this.refundForm.id,
              refund_amount: this.refundForm.refund_amount,
              reason: this.refundForm.reason
            });
            if (res.code === 0) {
              this.$message.success("退款申请提交成功");
              this.refundVisible = false;
              this.onSearch();
            } else {
              this.$message.error(res.message || "退款申请提交失败");
            }
          } catch (error) {
            this.$message.error("退款申请提交失败");
          } finally {
            this.refundLoading = false;
          }
        }
      });
    },
    async queryWxPayment(row) {
      try {
        this.$message.info("正在查询支付状态...");
        const res = await http.officeOrder.queryWxPayment(row.id);
        if (res.code === 0) {
          this.$message.success("查询成功");
          this.onSearch();
        } else {
          this.$message.error(res.message || "查询支付状态失败");
        }
      } catch (error) {
        this.$message.error("查询支付状态失败");
      }
    },
    formatTableData(tableData) {
      // 可以在这里对表格数据进行处理
    },
    onSearch() {
      this.pageNo = 1;
      this.initData();
      this.getStatistics();
    }
  }
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}
.statistics-box {
  margin-bottom: 20px;
}
.stat-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
}
.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
.order-info {
  margin-bottom: 20px;
}
.order-info h3 {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}
.info-item {
  margin-bottom: 10px;
}
.info-item .label {
  color: #606266;
  margin-right: 5px;
}
.amount-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}
</style>
